package com.wx_shop.api.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.wx_shop.api.domain.ProOrder;
import com.wx_shop.api.domain.ProOrderitem;
import com.wx_shop.api.domain.gen.ProOrderCriteria;
import com.wx_shop.api.domain.gen.ProOrderitemCriteria;
import com.wx_shop.api.mapper.ProOrderMapper;
import com.wx_shop.api.mapper.ProOrderitemMapper;
import com.wx_shop.api.service.OrderService;
import com.wx_shop.api.util.BeanUtil;
import com.wx_shop.api.vo.BaseReq;
import com.wx_shop.api.vo.BaseRes;
import com.wx_shop.api.vo.DataPageWrapper;
import com.wx_shop.api.vo.OrderVo;
import com.wx_shop.api.vo.OrderitemVo;

@Service
public class OrderServiceImpl implements OrderService {

	@Autowired
	private ProOrderMapper orderMapper;
	
	@Autowired
	private ProOrderitemMapper orderitemMapper; 
	
	@Override
	public BaseRes<DataPageWrapper<OrderVo>> fetchPageOrder(BaseReq<OrderVo> baseReq) {
		
		int currPage = baseReq.getCurrPage();
		int pageSize = baseReq.getPageSize();
		
		int mysqlLength = pageSize;
		int mysqlOffset = (currPage - 1) * pageSize;
		
		OrderVo pOrderVo = baseReq.getData();
		
		ProOrderCriteria mProOrderCriteria = new ProOrderCriteria();
		mProOrderCriteria.setMysqlLength(mysqlLength);
		mProOrderCriteria.setMysqlOffset(mysqlOffset);
		mProOrderCriteria.setOrderByClause(" update_time desc ");
		ProOrderCriteria.Criteria criteria = mProOrderCriteria.createCriteria();
		if( null != pOrderVo ) {
			if( pOrderVo.getStatus() != null ) {
				criteria.andStatusEqualTo(pOrderVo.getStatus());
			}
		}
		
		List<OrderVo> orderVos = new ArrayList<OrderVo>();
		
		/** query total page */
		long totalCount = orderMapper.countByExample(mProOrderCriteria);
		
		List<ProOrder> orders = orderMapper.selectByExample(mProOrderCriteria);
		for( int i=0; i<orders.size(); i++ ) {
			
			ProOrder rProOrder = orders.get(i);
			OrderVo orderVo = BeanUtil.voConvert(rProOrder, OrderVo.class);
			
			ProOrderitemCriteria mProOrderitemCriteria = new ProOrderitemCriteria();
			mProOrderitemCriteria.createCriteria()
			.andOrderidEqualTo(rProOrder.getId());
			
			List<ProOrderitem> orderItems = orderitemMapper.selectByExample(mProOrderitemCriteria);
			List<OrderitemVo> itemVos = BeanUtil.voConvertList(orderItems, OrderitemVo.class);
			
			orderVo.setItems(itemVos);
			orderVos.add(orderVo);
		}
		
		
		BaseRes<DataPageWrapper<OrderVo>> res = new BaseRes<DataPageWrapper<OrderVo>>();
		res.setData(new DataPageWrapper<OrderVo>());
		res.getData().setTotalCount(totalCount);
		res.getData().setCurrPage(currPage);
		res.getData().setPageSize(pageSize);
		res.getData().setRows(orderVos);
		
		int totalPage = (int) (totalCount % pageSize == 0 ? totalCount % pageSize : totalCount % pageSize + 1 );
		res.getData().setTotalPage(totalPage);
		
		return res;
	}

}
